package com.web.hr.Utils;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;

/**
 * @author LJ
 * @Description 关于URL的公共操作工具类
 * @Date 2016年6月14日 上午10:36:08
 * @Version v1.0
 */
public class URLCommonUtil {
    static Logger logger = Logger.getLogger(URLCommonUtil.class);
    private final static String UTF8 = "UTF-8";
    private final static String ISO88591 = "ISO-8859-1";
    private final static Integer COOKIEAGE = 0;

    /**
     * 处理get请求中文乱码的问题 即字符串ISO-8859-1转换为UTF-8
     *
     * @param source 源字符串
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String handleISO2UTF8(String source) throws UnsupportedEncodingException {
        if (StringUtils.isEmpty(source)) {
            return "";
        }
        return new String(source.getBytes(ISO88591), UTF8);
    }

    /**
     * post请求
     *
     * @param url     请求路径
     * @param params  参数
     * @param headers 请求头
     * @return
     */
    public static String doPost(String url, Map<String, String> params, Map<String, String> headers) {
        HttpPost httpPost = new HttpPost(url);
        logger.info("URL:" + url);
        String info = null;
        try {
            HttpClient httpClient = new DefaultHttpClient();
            //添加头部信息
            if (!CollectionUtils.isEmpty(headers)) {
                for (Entry<String, String> entry : headers.entrySet()) {
                    logger.info("-H  key:" + entry.getKey() + " value:" + entry.getValue());
                    httpPost.setHeader(new BasicHeader(entry.getKey(), entry.getValue()));
                }
            }
            //添加请求参数
            if (!CollectionUtils.isEmpty(params)) {
                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                for (Entry<String, String> entry : params.entrySet()) {
                    logger.info("-P  key:" + entry.getKey() + " value:" + entry.getValue());
                    nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                httpPost.setEntity(new UrlEncodedFormEntity(nvps, UTF8));
            }
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            info = EntityUtils.toString(entity, UTF8);
            logger.info("-R " + info);
            return info;
        } catch (Exception e) {
            info = "{code:0,msg:YWApi " + e.getMessage() + "}";
            logger.error(e.getMessage());
            e.printStackTrace();
        } finally {
            httpPost.releaseConnection();
        }
        return info;
    }

    /**
     * post请求
     *
     * @param url    请求路径
     * @param params 参数
     * @return
     */
    public static String doPost(String url, Map<String, String> params) {
        return doPost(url, params, null);
    }

    /**
     * get 请求
     *
     * @param url 请求路径
     * @return
     */
    public static String doGet(String url) {
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpClient httpClient = new DefaultHttpClient();

            HttpResponse response = httpClient.execute(httpGet);

            HttpEntity entity = response.getEntity();

            String info = EntityUtils.toString(entity, UTF8);
            return info;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpGet.releaseConnection();
        }
        return null;
    }

    /**
     * 从cookie中获取值
     *
     * @param request
     * @return
     */
    public static String getValueInCookie(HttpServletRequest request, String name) throws UnsupportedEncodingException {
        String userToken = "";
        for (int i = 0; request.getCookies() != null && i < request.getCookies().length; i++) {
            Cookie cookie = request.getCookies()[i];
            if (cookie.getName().equals(name)) {
                userToken = URLDecoder.decode(cookie.getValue(), UTF8);
                break;
            }
        }
        return userToken;
    }

    /**
     * 创建cookie
     *
     * @param response
     * @param name     名称
     * @param value    值
     */
    public static void makeCookie(HttpServletResponse response, String name, String value, String uri, Integer age) throws UnsupportedEncodingException {
        logger.info(URLEncoder.encode(value, UTF8));
        Cookie cookie = new Cookie(name, URLEncoder.encode(value, UTF8));
        cookie.setPath(uri);
        cookie.setMaxAge(age != null ? age : COOKIEAGE);// 默认0秒 即删除该Cookie
        response.addCookie(cookie);
    }

    /**
     * 中转文件
     *
     * @param file 上传的文件
     * @return 响应结果
     */
    public static String httpClientUploadFile(MultipartFile file, String remoteUrl) {
        final String remote_url = remoteUrl;// 第三方服务器请求地址
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = "";
        try {
            String fileName = file.getOriginalFilename();
            logger.info("-FN " + fileName);
            HttpPost httpPost = new HttpPost(remote_url);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody("file", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, URLEncoder.encode(fileName, "UTF-8"));// 文件流
            builder.addTextBody("filename", fileName);// 类似浏览器表单提交，对应input的name和value
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);// 执行提交
            HttpEntity responseEntity = response.getEntity();
            result = EntityUtils.toString(responseEntity, UTF8);
            logger.info("-R " + result);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 获取UUID码
     */
    public static String getUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
}
